<?php
if (!class_exists('Mysql'))
{
	define('FETCH_TYPE_BOTH', 0x01, true);
	define('FETCH_TYPE_NUM', 0x02, true);
	define('FETCH_TYPE_ASSOC', 0x04, true);
	define('FETCH_TYPE_OBJECT', 0x08, true);

	class Mysql
	{
		var $_link;
		var $_resource;
		var $_debug;
		var $_last_sql;

		function __construct()
		{
			$this->_link		= false;
			$this->_resource	= false;
			$this->_debug		= false;
			$this->_last_sql	= '';
		}

		function Mysql()
		{
			$this->__construct();
		}

		function __destruct()
		{
			if ($this->_link !== false)
			{
				mysql_close($this->_link);
				$this->_link = false;
			}
		}

		function connect($server, $user, $pass)
		{
			if ($this->_link !== false) return $this->_link;
			$this->_link = mysql_connect($server, $user, $pass);
			return $this->_link;
		}

		function select_db($database)
		{
			return mysql_select_db($database, $this->_link);
		}

		function disconnect()
		{
			$link = $this->_link;
			$this->_link = false;
			return mysql_close($link);
		}

		function query($sql)
		{
			if ($this->_debug) die($sql);
			$this->_last_sql = $sql;
			$this->_resource = mysql_query($sql, $this->_link);
			if (!$this->_resource) $this->error();
			return $this->_resource;
		}

		function get_num_rows()
		{
			return mysql_num_rows($this->_resource);
		}

		function get_affected_rows()
		{
			return mysql_affected_rows($this->_link);
		}

		function clear($res=null)
		{
			if (!$res) $res = $this->_resource;
			return mysql_free_result($res);
		}

		function close()
		{
			$this->disconnect();
		}

		function free_result($res=null)
		{
			return $this->clear($res);
		}

		function seek($position)
		{
			return mysql_data_seek($this->_resource, $position);
		}

		function fetch($type=FETCH_TYPE_ASSOC, $res=null)
		{
			$record = FALSE;
			if (!$res) $res = $this->_resource;

			switch ($type)
			{
				case FETCH_TYPE_BOTH :
					$record = mysql_fetch_array($res);
					break;
				case FETCH_TYPE_NUM :
					$record = mysql_fetch_row($res);
					break;
				case FETCH_TYPE_ASSOC :
					$record = mysql_fetch_assoc($res);
					break;
				case FETCH_TYPE_OBJECT :
					$record = mysql_fetch_object($res);
					break;
			}
			return $record;
		}

		function debug()
		{
			$this->_debug = true;
		}

		function error()
		{
			print "<meta http-equiv='content-type' content='text/html; charset=euc-kr'>";
			print "<br><br>";
			print "<table border='0' width='100%'>";
			print "<tr bgcolor='#6699CC'><td><font color='#FFFFFF'><b>" . mysql_errno() . " : " . mysql_error() . "</b></td></tr>";
			print "<tr bgcolor='#C9DCEB'><td>" . $this->_last_sql . "</td></tr>";
			print "</table>";
			exit;
		}

		function insert_id()
		{
			return mysql_insert_id($this->_link);
		}
	};
}
?>